package com.qf.controller;

import com.qf.pojo.Order;
import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.print.attribute.standard.PrinterURI;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

//@RestController
//@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private Random random = new Random();
    private AtomicInteger i = new AtomicInteger(0);

    //注入一个负载均衡器对象
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {

     /*   //通过服务发现客户端发现我们需要的服务
        List<ServiceInstance> instances = discoveryClient.getInstances("QF-ORDER");

        //模拟随即负载均衡策略
//        int idx = random.nextInt(instances.size());
//        ServiceInstance instance = instances.get(idx);

        //模拟轮询负载均衡
        int idx = i.incrementAndGet() % instances.size();
        ServiceInstance instance = instances.get(idx);*/

        //根据负载均衡策略，从指定名称的服务列表中选择一台机器 （默认是轮询策略）
        ServiceInstance instance = loadBalancerClient.choose("QF-ORDER");

        String host = instance.getHost();
        int port = instance.getPort();

        //发起远程访问，访问order服务
        R r = restTemplate.getForObject("http://"+host+":"+port+"/order/" + id, R.class);

        return r;
    }
}
